<template>
    <div id="MemberCard">
        <div>
            <el-card class="box-card">
                <el-row>
                <el-col :span="8"> 
                    <el-input
                    placeholder="请输入会员卡名称"
                    v-model="cardName"
                    clearable>
                    </el-input>
                </el-col>
                <el-col :span="2" :offset="1"><el-button icon="el-icon-search" @click="getCardByPage" circle></el-button></el-col>
                <el-col :span="2"><el-button type="primary" @click="addRole" round>新增</el-button></el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-table
                            :data="productData"
                            border
                            style="width:100%">
                            <el-table-column
                            fixed
                            prop="id"
                            label="序号"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="cardName"
                            label="会员卡名称"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="cardNumber"
                            label="会员卡编号"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="remarks"
                            label="会员卡使用说明"
                            >
                            </el-table-column>
                            <el-table-column
                            fixed="right"
                            label="操作"
                            width="200">
                            <template slot-scope="scope">
                                <el-button @click="handleClick(scope.row)" type="text" size="small" >查看</el-button>
                                <el-button @click="handleUpdate(scope.row)" type="text" size="small">编辑</el-button>
                                <el-button @click="deleteCard(scope.row)" type="text" size="small" style="color: red;">删除</el-button>
                            </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
                <el-row style="text-align: center;">
                    <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage4"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="page.total">
                </el-pagination>          
                </el-row>
            </el-card>
            <!-- 数据新增功能 -->
            <el-dialog title="新增会员卡" :visible.sync="dialogFormVisible" @close="handleClose('productForm')">
            <el-form :model="productForm" :rules="rules" ref="productForm">
                <el-form-item label="会员卡名称" :label-width="formLabelWidth" prop="cardName">
                    <el-input v-model="productForm.cardName" autocomplete="off" ></el-input>
                </el-form-item>
                <el-form-item label="会员卡编号" :label-width="formLabelWidth" prop="cardNumber">
                    <el-input v-model="productForm.cardNumber" autocomplete="off" ></el-input>
                </el-form-item>
                <el-form-item label="会员卡使用说明" :label-width="formLabelWidth">
                    <el-input v-model="productForm.remarks" autocomplete="off" ></el-input>
                </el-form-item>
                <el-form-item label="会员卡封面" :label-width="formLabelWidth">
                         <el-upload
                            style="text-align: center;"
                            class="avatar-uploader"
                            action="http://127.0.0.1:8082/uploadPicture"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveCard('productForm')">确 定</el-button>
            </div>
            </el-dialog>
            <!-- 数据查看功能 -->
            <el-dialog title="查看详情" :visible.sync="dialogFormVisibleDatil">
                <el-form :model="productFormList">
                    <el-form-item label="会员卡名称" :label-width="formLabelWidth" prop="cardName">
                        <el-input v-model="productFormList.cardName" autocomplete="off" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="会员卡编号" :label-width="formLabelWidth" prop="cardNumber">
                        <el-input v-model="productFormList.cardNumber" autocomplete="off" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="会员卡使用说明" :label-width="formLabelWidth">
                        <el-input v-model="productFormList.cardExplain" autocomplete="off" :disabled="true"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisibleDatil = false">关闭</el-button>
                </div>
            </el-dialog>
            <!-- 数据修改功能 -->
            <el-dialog title="会员卡编辑" :visible.sync="dialogFormVisibleUpdate" @close="handleClose('productFormEdit')">
                <el-form :model="productFormEdit" :rules="rulesEdit" ref="productFormEdit">
                    <el-form-item label="会员卡名称" :label-width="formLabelWidth" prop="cardName">
                        <el-input v-model="productFormEdit.cardName" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="会员卡编号" :label-width="formLabelWidth" prop="cardNumber">
                        <el-input v-model="productFormEdit.cardNumber" autocomplete="off" ></el-input>
                    </el-form-item>
                    <el-form-item label="会员卡使用说明" :label-width="formLabelWidth">
                        <el-input v-model="productFormEdit.remarks" autocomplete="off" ></el-input>
                    </el-form-item>
                    <el-form-item label="会员卡封面" :label-width="formLabelWidth">
                         <el-upload
                            style="text-align: center;"
                            class="avatar-uploader"
                            action="http://127.0.0.1:8082/uploadPicture"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisibleUpdate = false">取 消</el-button>
                    <el-button type="primary" @click="updateCard('productFormEdit')">确 定</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
  
</template>

<script>
const axios = require('axios');
export default {
   name: 'MemberCard',
        data(){
            //校验新增中会员卡名称是否为空或者名称是否正确或者是否重复
            var cardName = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入会员卡名称'));
                } else if  (value !=='' ) {
                    axios.get("http://127.0.0.1:8082/card/selectCardName?cardName="+value).then(res=>{
                        this.cardNameList=res.data.obj
                        this.cardNameList.forEach(item=>{
                            this.checkCardName=item.cardName
                        })
                        if(this.checkCardName===value){
                            callback(new Error('该会员卡已录入'));
                        }
                        else{
                             callback();
                        }
                    })
                }else{
                    callback(new Error('请输入正确的会员卡名称比如:季卡、月卡'));
                }
            };
            //校验新增中会员卡编号是否为空
            var cardNumber = (rule, value, callback) => {
                if(value===''){
                     callback(new Error('请输入会员卡编号'));
                }else{
                    callback();
                }
            };
            //校验新增中会员卡编号是否为空
            var cardNumberEdit = (rule, value, callback) => {
                if(value===''){
                     callback(new Error('请输入会员卡编号'));
                }else{
                    callback();
                }
            };
            //修改校验会员卡名称是否重复录入
            var cardNameEdit= (rule, value, callback) => {
                debugger
                if( value===''){
                     callback(new Error('请输入会员卡名称'));
                }else if(this.updateCardName === value){
                    callback();
                }else{
                    if(this.updateCardName !== value){
                            axios.get("http://127.0.0.1:8082/card/selectCardName?cardName="+value).then(res=>{
                            this.cardNameList=res.data.obj
                            this.cardNameList.forEach(item=>{
                                this.checkCardName=item.cardName
                            })
                            if(this.checkCardName===value){
                                callback(new Error('该会员卡已录入'));
                            }
                            else{
                                callback();
                            }
                        })
                    }
                }
            };  
            return {
                updateCardName:'',
                imageUrl:"",
                imageFile:File,
                cardName:'',//分页模糊查查询字段（会员卡名称）
                checkCardName:'',//新增校验会员卡名是否重复查询结果名称
                cardNameList:[],//新增校验会员卡名是否重复查询结果集合
                productData: [],//分页全查存放的数组
                dialogFormVisible: false,//新增弹框true弹出
                dialogFormVisibleDatil:false,//查看弹框true弹出
                dialogFormVisibleUpdate:false,//修改弹框true弹出
                productForm: {// 新增时使用到的form对象
                    id:'', //会员卡id
                    cardName:'', //会员卡名称
                    cardLevel:'',//会员卡等级
                    cardNumber:'', //会员卡编号
                    coverId:'', //会员卡封面id
                    remarks:'',//会员卡备注
                    imageId:'' //会员卡图片id
                },
                productFormList:{//查看时使用到的form对象
                    id:"",
                    cardName:'', //会员卡名称
                    cardLevel:'',//会员卡等级
                    cardNumber:'', //会员卡编号
                    cardExplain:'' //会员卡使用说明
                },
                productFormEdit:{// 修改时使用到的form对象
                    id:"",
                    cardName:'', //会员卡名称
                    cardLevel:'',//会员卡等级
                    cardNumber:'', //会员卡编号
                    coverId:'', //会员卡封面id
                    remarks:'',//会员卡备注
                    imageId:'' //会员卡图片id
                },
                formLabelWidth: '120px',
                currentPage4: 1,//分页当前选中页
                page:{
                    pageSize:10,//条数
                    pageNum:1,//页数
                    total:0
                },
                tatal:0,
                defaultProps: {
                    children: 'childs',
                    label: 'menuName'
                },
                //新增校验规则
                rules: {
                    cardName: [
                        { validator: cardName, trigger: 'blur' }
                    ],
                    cardNumber: [
                        { validator: cardNumber, trigger: 'blur' }
                    ],
                },
                //修改校验规则
                rulesEdit:{
                    cardNumber: [
                        { validator: cardNumberEdit, trigger: 'blur' }
                    ],
                    cardName: [
                        { validator: cardNameEdit, trigger: 'blur' }
                    ]
                }
            }
        },
        methods:{
             //新增修改清空值
            handleClose(formName) {
                this.productForm.cardName=''
                this.productForm.cardNumber=''
                this.productFormEdit.cardName=''
                this.productFormEdit.cardNumber=''
                this.imageUrl=''
                this.$refs[formName].resetFields()// 重置数据，同时也取消了表单的校验 refundFormData：el-form用ref绑定的值，
            },
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePreview(file) {
                console.log(file);
            },
            // 分页
            handleSizeChange(ps) {
                this.page.pageSize=ps;
                this.getCardByPage()
                console.log(`每页 ${val} 条`);
            },
            handleCurrentChange(pn) {
                this.page.pageNum=pn;
                this.getCardByPage()
            },
            //会员卡分页查+模糊查（会员卡名称）
            getCardByPage () {
                axios.get('http://127.0.0.1:8082/card/getCardByPage', {
                    params: {
                        cardName: this.cardName,
                        pageSize: this.page.pageSize,
                        pageNum: this.page.pageNum
                    }
                })
                    .then((res) => {
                        this.productData = res.data.content
                        this.page.total = res.data.total
                    })
            },
            //新增会员卡类型
            saveCard(formName){
                var formdata = new FormData();
                formdata.set("cardName",this.productForm.cardName)
                formdata.set("cardLevel",this.productForm.cardLevel)
                formdata.set("remarks",this.productForm.remarks)
                formdata.set("cardNumber",this.productForm.cardNumber)
                if(this.imageFile.name!="File"){
                    formdata.set("file",this.imageFile,this.imageFile.name)
                }
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        axios.post("http://127.0.0.1:8082/card/saveCard",formdata).
                        then(res => {
                            if(res.data.obj>0){
                                this.message("恭喜你，保存数据成功！","success")
                                this.dialogFormVisible = false
                                this.productForm={
                                    cardName:'', //会员卡名称
                                    cardLevel:'',//会员卡等级
                                    cardNumber:'', //会员卡编号
                                    cardPrice:'', //会员卡价格
                                    cardExplain:'' //会员卡使用说明
                                }
                                this.getCardByPage()
                            }else{
                                this.message("对不起，保存失败！","warning")
                            }
                        }).catch(error => {
                            this.$message.error('服务器崩溃了，请稍后再尝试使用！');
                        })
                    }else {
                        return false;
                    }
                });
            },
            //修改会员卡类型
            updateCard(formName){
                debugger
                var formdata = new FormData();
                formdata.set("id",this.productFormEdit.id)
                formdata.set("cardName",this.productFormEdit.cardName)
                formdata.set("cardLevel",this.productFormEdit.cardLevel)
                formdata.set("cardNumber",this.productFormEdit.cardNumber)
                formdata.set("remarks",this.productFormEdit.remarks)
                formdata.set("coverId",this.productFormEdit.coverId)
                formdata.set("imageId",this.productFormEdit.imageId)
                if(this.imageFile.name!="File"){
                    formdata.set("file",this.imageFile,this.imageFile.name)
                }
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        axios.put("http://127.0.0.1:8082/card/updateCard",formdata)
                        .then(res=>{
                            if(res.data.code==='200'){
                            this.message("恭喜你，修改数据成功！","success")
                                    this.dialogFormVisibleUpdate = false
                                    this.imageUrl = ''
                                    this.imageFile=File
                                    this.productFormEdit={
                                        cardName:'', //会员卡名称
                                        cardLevel:'',//会员卡等级
                                        cardNumber:'', //会员卡编号
                                        cardPrice:'', //会员卡价格
                                        cardExplain:'' //会员卡使用说明
                                    }
                                    this.getCardByPage();// 重新渲染数据列表
                            }else{
                                    this.message("对不起，修改失败！","warning")
                                }
                            }).catch(error => {
                                this.$message.error('服务器崩溃了，请稍后再尝试使用！');
                        })
                    }
                });
            },
            //删除会员卡类型
            deleteCard(row){
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }//删除提示框
                ).then(() => {
                    axios.delete("http://127.0.0.1:8082/card/deleteCard?id="+row.id)
                .then(res =>{
                    if(res.data.code==='200' ){
                        this.message("恭喜你，删除成功！","success")
                        this.getCardByPage()
                    }else{
                        this.message('删除失败','warning')
                    }
                }).catch(error =>{
                        alert(error)
                })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
                });
            },
             // 图片上传之后的方法
            handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);
            },
            // 图片上传之前的校验方法
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/png' || 'image/jpg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                this.imageFile = file
                this.imageUrl = URL.createObjectURL(file);
                return false;
            },
            //消息提示框
            message(message,type){
                this.$message({
                    message:message,
                    type: type
                });
            },
            //查看按钮回显值
            handleClick(row){
                this.dialogFormVisibleDatil = true
                this.productFormList=row
            },
            //修改按钮回显值
            handleUpdate(row){
                this.dialogFormVisibleUpdate=true
                this.imageUrl='http://127.0.0.1:8082/getImageById?id='+row.coverId
                this.productFormEdit.cardName=row.cardName
                this.productFormEdit.cardNumber=row.cardNumber
                this.productFormEdit.cardPrice=row.cardPrice
                this.productFormEdit.cardLevel=row.cardLevel
                this.productFormEdit.remarks=row.remarks
                this.productFormEdit.coverId=row.coverId
                this.productFormEdit.id = row.id
                this.updateCardName = row.cardName
            },
            //新增按钮弹出弹框
            addRole(){
                this.dialogFormVisible = true
            },
        },
        //初始化加载数据
        mounted(){
            this.getCardByPage()//分页全查+模糊查（会员卡名称）
        }, 
}
</script>
<style>
/**
        * 附件上传样式
        */
        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
        .el-icon-arrow-down {
        font-size: 12px;
     }
     .box-card {
    height: 100%;
    }
</style>